/* 
 * File:   Instance.cpp
 * Author: neuma173
 * 
 * Created on March 30, 2011, 4:33 PM
 */

#include "Instance.h"

Instance::Instance() {
}

Instance::Instance(Shape* shape)
{
    this->shape = shape;
    TMatrix.SetIdentity();
    ITMatrix.SetIdentity();
    this->shader = shape->GetShader();
}

Instance::Instance(const Instance& orig) {
}

Instance::~Instance() {
}

void Instance::Rotate(double degrees, int axis)
{
    TMatrix.Rotate(degrees, axis);
}

void Instance::Translate(double dx, double dy, double dz)
{
    TMatrix.Translate(dx, dy, dz);
}

void Instance::Scale(double sx, double sy, double sz)
{
    TMatrix.Scale(sx, sy, sz);
}

bool Instance::TestIntersect(Ray &ray, double tmin, double tmax, HitStruct& hitStruct)
{
    Vector3D tOrigin = ITMatrix.Transform(ray.GetOrigin());
    Vector3D tDirection = ITMatrix.Transform(ray.GetOrigin() + ray.GetDirection());
    tDirection -= tOrigin;
    //tDirection.normalize();
    Ray tRay = Ray(tOrigin, tDirection);
    //optimize this
    bool hit = shape->TestIntersect(tRay, tmin, tmax, hitStruct);
    hitStruct.shader = this->shader;
    hitStruct.normal = ITMatrix.TransposeTransform(hitStruct.normal);
    hitStruct.normal.normalize();
    return hit;
}
//const Vector3D Instance::SurfaceNormal(Ray &ray)
//{
//    //Might need to run ray through the transform
//    return shape->SurfaceNormal(ray);
//}
double Instance::GetSortValue(int sortBy)
{
    if(sortBy == X_VAL){
        return (GetBoundingBox()->GetXMax() + GetBoundingBox()->GetXMin())/2.0;
    }
    if(sortBy == Y_VAL){
        return (GetBoundingBox()->GetYMax() + GetBoundingBox()->GetYMin())/2.0;
    }
    if(sortBy == Z_VAL){
        return (GetBoundingBox()->GetZMax() + GetBoundingBox()->GetZMin())/2.0;
    }
}
void Instance::SetShader(Shader* shader)
{
    this->shader = shader;
}
Shader* Instance::GetShader()
{
    return shader;
}

void Instance::Finalize()
{
    this->ITMatrix = TMatrix.GetInverse();
    this->boundingBox = new BoundingBox (*shape->GetBoundingBox());
    boundingBox->Transform(TMatrix);
}

